import express, { Application } from 'express'
import bodyParse from 'body-parser'
import { UReadFileSync, UWriteFileSync, fileOperation } from './utils'
import { ITodoData } from '../src/js/typing'
import { ITodoItem } from './typing'

const app: Application = express()

app.use(bodyParse.urlencoded({ extended: true }))
app.use(bodyParse.json())



app.all("*", function (req, res, next) {
    // 设置允许跨域的域名,*代表允许任意域名跨域
    res.header('Access-Control-Allow-Origin', '*');
    // 允许的header类型
    res.header('Access-Control-Allow-Headers', 'content-type');
    // 跨域允许的请求方式
    res.header('Access-Control-Allow-Methods', 'DELETE,PUT,POST,GET,OPTIONS');
    next();
})

app.get('/todolist', (req, res) => {
    const todoList: string = fileOperation('todo.json')
    res.send(todoList)
})

app.post('/add', (req, res) => {

    const ITodoData: ITodoData = JSON.parse(req.body.todo)

    console.log(typeof ITodoData.complete)
    fileOperation('todo.json', (res: ITodoItem[]) => {
        const { content, complete } = ITodoData
        console.log(typeof complete)
        const findItodo: ITodoData | undefined = res.find((item: ITodoData) => item.content === content)
        if (findItodo) {
            return false
        } else {
            return [...res, ITodoData]
        }
    })
    res.send({
        code: 200,
        msg: '添加成功'
    })
})

app.post('/remove', (req, res) => {
    const id = parseInt(req.body.id)
    fileOperation('todo.json', (todolist: ITodoData[]) => {
        return todolist.filter((todoItem: ITodoData) => todoItem.id !== id)
    })
    res.send({
        code: 200,
        msg: '删除成功'
    })
})

app.post('/toggle', () => { })


app.listen('8111', () => {
})
